import json

import jwt
import datetime


from jwt import exceptions
from django.core.cache import cache
from rest_framework.response import Response
# 加的盐
JWT_SALT = "ds()udsjo@jlsdosjf)wjd_#(#)$"


def create_token(data, timeout=8):
    en_dict = {
        'exp': datetime.datetime.now() + datetime.timedelta(hours=timeout),  # 过期时间
        'iat': datetime.datetime.now(),  # 开始时间
        'data': data
    }
    ret_s = jwt.encode(en_dict, JWT_SALT, algorithm='HS256')  # 加密生成字符串
    return ret_s


def parse_token(token):
    """
    用于解密
    :param token:
    :return:
    """
    result = {"status": False, "data": None, "error": None}
    try:
        # 进行解密
        # token = bytes(token, 'utf-8')
        verified_payload = jwt.decode(token, JWT_SALT, algorithms=['HS256'])
        result["status"] = True
        result['data'] = verified_payload
    except exceptions.ExpiredSignatureError:
        result['error'] = '40001'
    except jwt.DecodeError:
        result['error'] = '40002'
    except jwt.InvalidTokenError:
        result['error'] = '40003'
    return result


def user_Auth(request):
    token = request.META.get('HTTP_AUTHORIZATION')
    result = parse_token(token)
    if result["status"]:
        # cache.set('user', 'mo111', 100)
        # print(result["data"]['data'])
        user_token = cache.get(str(result["data"]['data']['userinfo'][0]['id']))
        # user = models.Loginuser.objects.filter(id=result["data"]['data']['userid']).last()
        if user_token == token:
            token_time = 60 * 30
            # 用id加登录时间做键，就可以准许一个用户多次登录了
            cache.set(str(result["data"]['data']['userinfo'][0]['id']), token, token_time)
            return result["data"]['data']['userinfo'][0], result['error'], user_token, result["data"]['data']['logintime']
        else:
            return None, "40004", "asdfghjkl123456", None
    else:
        return None, result['error'], "asdfghjkl123456", None
token_code = {
    '40001': "token已失效",
    '40002': "token认证失败",
    '40003': "非法的token",
    '40004': "用户未登录",
    '40005': "用户无权限",
}


# 用户认证
def userAuth(func):
    def iner(*args, **kwargs):
        # print("执行前")
        print('userAuth',args)
        request = args[0]
        # print(request.META.get('HTTP_AUTHORIZATION'))
        userinfo, msg, token, logintime = user_Auth(request)
        # print()
        if userinfo is None:
            resp = {"code": -1, 'msg': token_code[msg]}
            return Response(resp)
        kwargs['userinfo'] = userinfo
        return func(*args, **kwargs)
        # print("执行后")
    return iner


def userCateAuth(func):
    def iner(*args, **kwargs):
        # print('userCateAuth：',args)
        userinfo = kwargs.get('userinfo')
        # print(userinfo, kwargs, args)

        if userinfo:
            cate = userinfo.get('cate')
            # print(cate)
            if cate > 0:
                return func(*args, **kwargs)
            else:
                resp = {"code": -1, 'msg': '用户无权限'}
                return Response(resp)
        else:
            resp = {"code": -1, 'msg': '用户未登录'}
            return Response(resp)
    return iner